package com.sxj.PDMS.controller.student;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxj.PDMS.common.BaseResponse;
import com.sxj.PDMS.common.ErrorCode;
import com.sxj.PDMS.common.Result;
import com.sxj.PDMS.controller.admin.AdminMessageController;
import com.sxj.PDMS.exception.BusinessException;
import com.sxj.PDMS.exception.ThrowUtils;
import com.sxj.PDMS.model.dto.student.YusRecordRequest;
import com.sxj.PDMS.model.dto.student.YusRecordUpdateRequest;
import com.sxj.PDMS.model.dto.student.YusRecordUploadRequest;
import com.sxj.PDMS.model.entity.YusIncompleteRecord;
import com.sxj.PDMS.model.entity.YusRecordSheet;
import com.sxj.PDMS.model.vo.PagingQueryResponse;
import com.sxj.PDMS.service.YusIncompleteRecordService;
import com.sxj.PDMS.service.YusRecordSheetService;
import com.sxj.PDMS.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/student")
@Slf4j
public class StudentYusRecordController {
    @Autowired
    private YusRecordSheetService yusRecordSheetService;
    @Autowired
    private YusIncompleteRecordService yusIncompleteRecordService;

    @Transactional
    @PostMapping("/upload_yusRecord")
    public BaseResponse yusRecordUpload(YusRecordUploadRequest yusRecordUploadRequest) throws IOException {
        log.info("青年大学习上传：{}", yusRecordUploadRequest);
        if (yusRecordUploadRequest.getStudentNumber() == null || yusRecordUploadRequest.getStudentNumber().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学生学号不能为空");
        }
        if (yusRecordUploadRequest.getGrade() == null || yusRecordUploadRequest.getGrade().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "年级不能为空");
        }
        if (yusRecordUploadRequest.getName() == null || yusRecordUploadRequest.getName().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "姓名不能为空");
        }
        if (yusRecordUploadRequest.getImageUrl() == null || yusRecordUploadRequest.getImageUrl().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
        // todo 文件大小进行限制50mb
        YusRecordRequest yusRecordRequest = new YusRecordRequest();
        yusRecordRequest.setStudentNumber(yusRecordUploadRequest.getStudentNumber());
        yusRecordRequest.setGrade(yusRecordUploadRequest.getGrade());
        yusRecordRequest.setName(yusRecordUploadRequest.getName());

        Boolean savedIncomplete = yusIncompleteRecordService.yusRecordUpload(yusRecordRequest);
        Boolean saved = yusRecordSheetService.yusRecordUpload(yusRecordUploadRequest);
        if (!saved) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        if (!savedIncomplete) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

        return Result.success();
    }

    @PostMapping("/upload_yusRecordFile")
    public String uploadYusRecordFile(@RequestPart(value = "uploadFile") MultipartFile uploadFile) {
        log.info("文件上传：{}", uploadFile);
        if (uploadFile != null && !uploadFile.isEmpty()) {
            synchronized (StudentYusRecordController.class) {
                //获取当前时间戳
                String flag = System.currentTimeMillis() + "";
                //获取文件名
                String fileName = uploadFile.getOriginalFilename();
                try {
                    //todo：/学生提交青年大学习的存放路径
                    String path = "D:\\user\\Desktop\\store\\YUS\\";
                    FileUtil.writeBytes(uploadFile.getBytes(), path + "\\" + flag + "-" + fileName);
                    System.out.println(fileName + "上传成功");
                    Thread.sleep(1L);
                } catch (Exception e) {
                    System.out.println(fileName + "上传失败");
                }
                return flag;
            }
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件不能为空");
        }
    }


    @DeleteMapping("/delete_yusRecord")
    public BaseResponse<Boolean> deleteYusRecord(Long id) {
        //todo：/学生提交青年大学习的存放路径
        String path = "D:\\user\\Desktop\\store\\YUS\\";
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        YusRecordSheet yusRecordSheet = yusRecordSheetService.getById(id);
        if (yusRecordSheet == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号所指数据不存在");
        }

        String studentNumber = yusRecordSheet.getStudentNumber();
        QueryWrapper<YusIncompleteRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_number", studentNumber);
        YusIncompleteRecord yusIncompleteRecord = yusIncompleteRecordService.getOne(queryWrapper);
        boolean b = yusIncompleteRecordService.removeById(yusIncompleteRecord.getId());

        String flag = yusRecordSheet.getImageUrl();
        boolean removed = yusRecordSheetService.removeById(id);
        if (!removed) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        if (!b) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        if (StrUtil.isNotEmpty(avatar)) {
            boolean isDeleted = FileUtil.del(path + avatar);
            if (isDeleted) {
                log.info("文件 {} 删除成功。", avatar);
            } else {
                log.error("文件 {} 删除失败。", avatar);
            }
        } else {
            log.warn("文件 {} 不存在，无需删除。", avatar);
        }
        return Result.success(true);
    }

    @Transactional
    @PutMapping("/modify_yusRecord")
    public BaseResponse<Boolean> updateYusRecord(@RequestBody YusRecordUpdateRequest yusRecordUpdateRequest,
                                                 HttpServletRequest request) throws IOException {
        if (yusRecordUpdateRequest == null || yusRecordUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数异常");
        }

        //todo : 文件提交位置
        String path = "D:\\user\\Desktop\\store\\YUS\\";
        //查看有没有要修改编号的记录
        YusRecordSheet oldYusRecordSheet = yusRecordSheetService.getById(yusRecordUpdateRequest.getId());
        if (oldYusRecordSheet == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号所指数据不存在");
        }
        //删除未完成的表中记录
        String studentNumber = oldYusRecordSheet.getStudentNumber();
        QueryWrapper<YusIncompleteRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_number", studentNumber);
        YusIncompleteRecord oldYusIncompleteRecord = yusIncompleteRecordService.getOne(queryWrapper);
        yusIncompleteRecordService.removeById(oldYusIncompleteRecord.getId());
        //删除旧文件
        List<String> fileNames = FileUtil.listFileNames(path);
        String avatar = fileNames.stream().filter(name -> name.contains(yusRecordUpdateRequest.getOldImageUrl())).findAny().orElse("");
        if (StrUtil.isNotEmpty(avatar)) {
            boolean isDeleted = FileUtil.del(path + avatar);
            if (isDeleted) {
                log.info("文件 {} 删除成功。", avatar);
            } else {
                log.error("文件 {} 删除失败。", avatar);
            }
        } else {
            log.warn("文件 {} 不存在，无需删除。", avatar);
        }
        //未完成的信息
        YusIncompleteRecord yusIncompleteRecord = new YusIncompleteRecord();
        yusIncompleteRecord.setStudentNumber(studentNumber);
        yusIncompleteRecord.setGrade(yusRecordUpdateRequest.getGrade());
        yusIncompleteRecord.setName(yusRecordUpdateRequest.getName());
        //提交的信息
        YusRecordSheet yusRecordSheet = new YusRecordSheet();
        yusRecordSheet.setId(yusRecordUpdateRequest.getId());
        yusRecordSheet.setGrade(yusRecordUpdateRequest.getGrade());
        yusRecordSheet.setName(yusRecordUpdateRequest.getName());
        yusRecordSheet.setStudentNumber(yusRecordUpdateRequest.getStudentNumber());
        // 更新消息
        boolean result = yusRecordSheetService.updateById(yusRecordSheet);
        //重新保存未完成的
        yusIncompleteRecordService.save(yusIncompleteRecord);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // todo 记录修改日志
//        log.info("{}:{}修改{}资料文件", new Date().now(), request.getSession().getAttribute("userId"), dataInformationListUpdateRequest.getDataName());

        return Result.success(true);
    }

    @GetMapping("/selectAll_yusRecord")
    public BaseResponse<PagingQueryResponse<YusRecordSheet>> selectYusRecord(@RequestParam(defaultValue = "1") Integer page,
                                                                             @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询 ：page:{}, pageSize:{}", page, pageSize);
        PagingQueryResponse<YusRecordSheet> pagingQueryResponse = yusRecordSheetService.selectAll(page, pageSize);
        return Result.success(pagingQueryResponse);

    }

    @GetMapping("/select_yusRecord")
    public BaseResponse<PagingQueryResponse<YusRecordSheet>> selectWithCondition(@RequestParam(defaultValue = "1") Integer page,
                                                                                 @RequestParam(defaultValue = "10") Integer pageSize,
                                                                                 YusRecordRequest yusRecordRequest) {

        PagingQueryResponse<YusRecordSheet> pagingQueryResponse = yusRecordSheetService.yusRecordSheetSelect(page, pageSize, yusRecordRequest);

        return Result.success(pagingQueryResponse);
    }
}
